/*
 * @Description: 字段匹配弹窗
 * @Author: Zzt
 * @Date: 2022-11-06 17:17:29
 * @LastEditTime: 2023-01-30 16:52:05
 */
import { jsonClone } from '@/utils';
import { Button, Select, Space, Table, Tabs } from 'antd';
import Column from 'antd/es/table/Column';
import { delItemById, editItemById, getListItemValue } from '@/utils/list';
import { v4 as uuidv4 } from 'uuid';
import { useEffect, useState } from 'react';
import { useMappingRelationContext } from '../../../contexts/MappingRelationContext';
import { ILevel } from '@/interfaces/archiveType';

const { TabPane } = Tabs;
const { Option } = Select;

class ExcelItem {
  key: string;

  fieldName: string = null;

  typeTitle: string = null;

  title: string = null;

  constructor(idx: number) {
    this.key = uuidv4();
  }
}
const relationship = [
  { id: 1, value: '等于' },
  { id: 2, value: '包含' },
  { id: 3, value: '属于' }
];
const FieldMatch = (props: any) => {
  const { updateTemplate, tplData } = props;
  // 当前选中的tab
  const [currentTab, setCurrentTab] = useState<string>('');
  // 表格内容
  const [initTable, setInitTable] = useState([]);
  const { hierachy, base } = useMappingRelationContext();
  const [levelList] = hierachy;
  // excel列与元数据字段关系
  const [colRelation, setColRelation] = useState<any[]>([]);
  useEffect(() => {
    if (tplData?.id) {
      tplData.levelList.forEach((level: any) => {
        // levelList 增加key
        level.relationList.forEach((item: any) => {
          item = {
            ...item,
            key: item.column + item.title
          };
        });
      });
      setColRelation(tplData.levelList);
    }
  }, [tplData]);
  useEffect(() => {
    if (levelList?.length > 0) {
      const highestLevel = levelList.find((level: ILevel) => level.levelNum === 1);
      setCurrentTab(`${highestLevel?.level}`);
    }
  }, [levelList]);

  useEffect(() => {
    // setInitTable
  }, [currentTab]);
  /**
   * @description: tab切换
   * @param {string} key 选中的tab的key
   */
  const tabsChange = (key: string) => {
    saveTableForm();
    setCurrentTab(key);
  };
  useEffect(() => {
    setCurrentTab(hierachy[0].key);
  }, []);
  /**
   * @description: 保存excel与元数据映射关系
   */
  const saveTableForm = () => {
    const newState = jsonClone(colRelation);
    if (newState.length > 0) {
      let flag: boolean = false;
      newState.forEach((item: any) => {
        if (item.level === parseInt(currentTab, 10)) {
          item.relationList = initTable;
          flag = true;
        }
      });
      if (!flag) {
        newState.push({
          level: parseInt(currentTab, 10),
          relationList: initTable
        });
      }
    } else {
      newState.push({
        level: parseInt(currentTab, 10),
        relationList: initTable
      });
    }
    setColRelation(newState);
    updateTemplate((state: any) => ({
      ...state,
      levelList: newState
    }));
    return newState;
  };
  /**
   * @description: 清空全部数据
   */
  const clearAll = () => {
    const initData: any = {
      typeTitle: null,
      fieldName: null,
      title: null
    };
    setInitTable((state) => state.map((item) => ({ ...item, ...initData })));
  };
  const deleteItem = (key: string) => {
    setInitTable(delItemById(key, initTable, 'key'));
  };
  /**
   * @description: 保存单元格操作选择的内容
   * @param {any} row
   */
  const handleSave = (row: any) => {
    const newData = jsonClone(initTable);
    const index = newData.findIndex((item: any) => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, { ...item, ...row });
    setInitTable(newData);
    console.log('12313123', newData);
  };
  return (
    <>
      <Tabs activeKey={currentTab} onChange={tabsChange}>
        {hierachy.map((level: any) => (
          <TabPane tab={`源"${level.beforeTypeName}">目标"${level.afterTypeName}"`} key={level.key}>
            <Space>
              <Button
                onClick={() => {
                  setInitTable((state) => [...state, new ExcelItem(state.length)]);
                }}
              >
                添加一行
              </Button>
              <Button
                onClick={() => {
                  clearAll();
                }}
              >
                删除
              </Button>
            </Space>
            <Table dataSource={initTable} size="small" pagination={false} bordered>
              <Column
                title="序号"
                key="idCol"
                align="center"
                render={(_val, _record, idx) => `${idx + 1}`}
              />
              <Column
                title={`源${level.beforeTypeName}字段`}
                dataIndex="title"
                key="title"
                align="center"
                render={(val, record: ILevel) => (
                  <Select
                    value={val}
                    style={{ width: 200 }}
                    placeholder="请选择字段"
                    size="small"
                    onChange={(value) => {
                      handleSave({ ...record, title: value });
                    }}
                  >
                    {/* {items.map((item: any) => (
                      <Option key={item.field_name} value={item.field_desc}>
                        {item.field_desc}
                      </Option>
                    ))} */}
                  </Select>
                )}
              />
              <Column
                title="关系"
                dataIndex="fieldName"
                key="fieldName"
                align="center"
                render={(val, record: any) => (
                  <Select
                    value={val}
                    style={{ width: 140 }}
                    size="small"
                    placeholder="请选择字段"
                    onChange={(value) => {
                      handleSave({ ...record, fieldName: value });
                    }}
                  >
                    {relationship.map((item: any) => (
                      <Option key={item.id} value={item.id}>
                        {item.value}
                      </Option>
                    ))}
                  </Select>
                )}
              />
              <Column
                title={`目标${level.afterTypeName}字段`}
                dataIndex="typeTitle"
                key="typeTitle"
                align="center"
                render={(val, record: any) => (
                  <Select
                    value={val}
                    style={{ width: 140 }}
                    size="small"
                    placeholder="请选择字段"
                    onChange={(value) => {
                      handleSave({ ...record, typeTitle: value });
                    }}
                  >
                    {/* {items.map((item: any) => (
                      <Option key={item.field_name} value={item.field_desc}>
                        {item.field_desc}
                      </Option>
                    ))} */}
                  </Select>
                )}
              />
              <Column
                title="操作"
                dataIndex="action"
                key="action"
                align="center"
                render={(_val, record: any) => (
                  <Button
                    type="link"
                    size="small"
                    danger
                    onClick={() => {
                      deleteItem(record.key);
                    }}
                  >
                    删除
                  </Button>
                )}
              />
            </Table>
          </TabPane>
        ))}
      </Tabs>
    </>
  );
};
export default FieldMatch;
